﻿using System;
using System.IO;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using FileAccess = DAL.File.FileAccess;

namespace BLL.Utils
{
    public static class Misc
    {
        public static PngBitmapEncoder ToPng(this BitmapSource image)
        {
            return new PngBitmapEncoder { Interlace = PngInterlaceOption.On, Frames = { BitmapFrame.Create(image) } };
        }

        public static void Serialize<T>(this FileAccess fs, string filePath, T obj)
        {
            fs.WriteFile(filePath, Serialize(obj));
        }

        public static byte[] Serialize<T>(T obj)
        {
            using (var ms = new MemoryStream())
            {
                new XmlSerializer(typeof (T)).Serialize(ms, obj);
                return ms.ToArray();
            }
        }

        public static T Deserialize<T>(this FileAccess fs, string filePath) where T : class
        {
            try
            {
                var inputBytes = fs.ReadFile(filePath);
                return inputBytes != null ? Deserialize<T>(inputBytes) : null;
            }
            catch
            {
                return null;
            }
        }

        public static T Deserialize<T>(byte[] data) where T : class
        {
            try
            {
                return (T) new XmlSerializer(typeof (T)).Deserialize(new MemoryStream(data));
            }
            catch
            {
                return null;
            }
        }

        public static void SafeInvoke(this Action action)
        {
            if (action != null)
                action();
        }
    }
}